package com.kingbook.core.scripting;

import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.exception.ParamsException;
import com.kingbook.core.exception.SQLParserException;
import com.kingbook.core.sql.SqlFactory;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.Reader;


/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
@Component
public class XmlFactory {

    private static Logger logger = LoggerFactory.getLogger(XmlFactory.class);

    @Value("${solidity.core.filePath}")
    private String sqlPath;

    private static final String XML_FILE_EXTENSION = ".xml";

    @PostConstruct
    public void init() {
        if (StringUtils.isNotEmpty(sqlPath)) {
            try {
                Resource[] sqlFiles = ResourcePatternUtils.getResourcePatternResolver(new PathMatchingResourcePatternResolver()).getResources(sqlPath);
                for (Resource sqlFile : sqlFiles) {
                    String filename = sqlFile.getFilename();
                    logger.info(">>>>>正在加载 SQL文件 : " + sqlFile);
                    try {
                        if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
                            EncodedResource enc = new EncodedResource(sqlFile, "utf-8");
                            SqlFactory.pushSqlTemplate(parseTemplate(enc.getReader(), filename));
                        }
                    } catch (IOException e) {
                        logger.error("读取SQL文件错误：" + filename, e);
                    }
                }
            } catch (Exception e) {
                logger.error("读取sql文件错误：", e);
            }
        } else {
            throw new ParamsException("SQL文件路径没有设置...[sql.filePath]", logger);
        }
    }

    private SqlTemplate	parseTemplate(Reader reader, String filename ) {
        Document document;
        try {
            document = new SAXBuilder().build(reader);
            return new SqlTemplate(document.getRootElement());
        }catch (Exception e){
            throw new SQLParserException("[SqlNode] 读取SQL文件错误：文件名=" + filename, e, logger);
        }
    }



}